package flyWeight;

// 坦克子弹池为例子

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * 子弹
 */
class Bullet{
    private UUID uuid;
    public boolean isLeaving = false;
    public Bullet(){
        this.uuid = UUID.randomUUID();
    }

    @Override
    public String toString() {
        return "Bullet{" +
                "uuid=" + uuid +
                ", isLeaving=" + isLeaving +
                '}';
    }
}

/**
 * 子弹池
 */
class BulletPool{
    // 维护子弹的内部池
    private List<Bullet> list = new ArrayList<>();

    public BulletPool(int poolNum){
        // 在子弹池里面创建子弹
        for(int i = 0; i < poolNum; i++){
            list.add(new Bullet());
        }
    }

    public Bullet getBullet(){
        for(Bullet bullet: list){
            if(!bullet.isLeaving) {
                bullet.isLeaving = true;
                System.out.println("由线程池创建");
                return bullet;
            }
        }
        System.out.println("线程池满了重新创建");
        Bullet bullet_child = new Bullet();
        bullet_child.isLeaving = true;
        list.add(bullet_child);
        return bullet_child;
    }

}

public class FlyWeight {
    public static void main(String[] args) {
        System.out.println("flyweight");
        BulletPool bulletPool = new BulletPool(100);
        for (int i =0; i< 102;i++) {
            Bullet bullet = bulletPool.getBullet();
            System.out.println(bullet);
        }

        String str = new String("string");
        System.out.println(str.intern());
    }
}
